import axios from 'axios';
import { Message } from 'element-ui';
const ENV = process.env.NODE_ENV;

function createdService(url) {
  const service = axios.create({
    baseURL: url,
    timeout: 50000000000
  });
  service.interceptors.request.use(
    config => {
      const token = localStorage.getItem('xcToken');
      if (token) {
        config.headers['Token'] = token;
      }
      return config;
    },
    error => {
      return Promise.reject(error);
    }
  );
  service.interceptors.response.use(
    response => {
      const res = response.data;
      if (res.code) {
        if (res.code === 10003) {
          Message({
            message: '登录过期，请重新登录',
            type: 'warning'
          });
          localStorage.removeItem('xcToken');
          localStorage.removeItem('dialogPhone');
          localStorage.removeItem('showAvatar');

          setTimeout(() => {
            window.location.reload();
          }, 500);
        }
      } else {
        if (res.code === 10003) {
          Message({
            message: '登录过期，请重新登录',
            type: 'warning'
          });
          localStorage.removeItem('xcToken');
          localStorage.removeItem('dialogPhone');
          localStorage.removeItem('showAvatar');
          setTimeout(() => {
            window.location.reload();
          }, 500);
        }
      }
      return res;
    },
    error => {
      Message({
        message: '暂无数据 ╮(╯▽╰)╭ ',
        type: 'warning',
        duration: 5 * 1000
      });
      return Promise.reject(error);
    }
  );
  return service;
}

const p = new Promise((resolve, reject) => {
  axios.get('config/app-config.json')
    .then((res) => {
      if (ENV === 'development') {
        // 本地线下地址
        // const basePath = 'http://115.239.175.246:5904/capital_back';
        // const basePath = 'http://115.239.175.246:5501/capital_back';
        // const basePath = 'http://115.239.175.246:5902/capital_back'; // 98外
        // const basePath = ' http://115.239.175.246:5503/capital_back';
        const basePath = 'http://10.10.10.61:8081/capital_back';
        // const basePath = 'http://10.10.10.98:8081/capital_back';
        // const basePath = 'http://10.10.10.95:8081/capital_back';
        // const basePath = 'http://10.10.10.31:8081/capital_back';
        // const basePath = 'http://10.10.10.32:8081/capital_back';
        // const basePath = 'http://10.10.10.52:6080/capital_back';
        resolve(createdService(basePath));
      } else {
        if (res.data.isAutoGet === '0') {
          resolve(createdService(res.data.baseUrl));
        } else {
          const autoUrl = `http://${window.location.host}/capital_back`;// 动态接口地址
          resolve(createdService(autoUrl));
        }
      }
    });
});

export default () => {
  return p;
};

